﻿using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using Microsoft.Phone.Controls;
using Microsoft.Devices.Sensors;
namespace PiggyBank
{
    public partial class Game : PhoneApplicationPage
    {
        Accelerometer accelerometer = new Accelerometer();
        public Game()
        {
            InitializeComponent();
            CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);
            Start(TimeSpan.Zero);
            gameCanvas.MouseLeftButtonDown += new MouseButtonEventHandler(gameCanvas_MouseLeftButtonDown);
            
            accelerometer.ReadingChanged += new EventHandler<AccelerometerReadingEventArgs>(accelerometer_ReadingChanged);
            accelerometer.TimeBetweenUpdates = TimeSpan.FromMilliseconds(500);
            accelerometer.Start();
            if (!isVibrate)
                Btn_isVibrate.Content = "Vibrate On";
            else
                Btn_isVibrate.Content = "Vibrate Off";
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            Touch.FrameReported += new TouchFrameEventHandler(Touch_FrameReported);
            base.OnNavigatedTo(e);
        }
        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            Touch.FrameReported -= (Touch_FrameReported);
            for (int i = gameCanvas.Children.Count - 1; i >= 0; i--)
            {
                var item = gameCanvas.Children[i] as IDisposable;
                if (item != null)
                    item.Dispose();
                gameCanvas.Children.RemoveAt(i);
            }

            base.OnNavigatedFrom(e);
        }
        bool isfrist = true;
        double o_x;
        double o_y;
        double o_z;
        double max_3Ddistance = 1;
        void accelerometer_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
        {
            if (isfrist)
            {
                isfrist = false;
                o_x = e.X;
                o_y = e.Y;
                o_z = e.Z;
                return;
            }

            var m_Height = Math.Abs(e.Z - o_y);
            var m_2Ddistance = Math.Sqrt((Math.Pow(e.X - o_x, 2) + Math.Pow(e.Y - o_y, 2))); 
            var m_3Ddistance=Math.Sqrt(Math.Pow(m_Height,2)+Math.Pow(m_2Ddistance,2)); 
            if(m_3Ddistance > max_3Ddistance)
            {
                max_3Ddistance += 0.5;
                this.Dispatcher.BeginInvoke(() => { AddGold(); });
                
                
            }
            o_x = e.X;
            o_y = e.Y;
            o_z = e.Z;
        }

        
        DateTime lasttime = DateTime.Now;
        void CompositionTarget_Rendering(object sender, EventArgs e)
        {
            if (!isRun)
                lasttime = DateTime.Now;
            else
            {
                TimeSpan timespan = DateTime.Now - lasttime;
                lasttime = DateTime.Now;
                runtime += timespan;
                UpdateToTime(runtime);
                if(max_3Ddistance>1)
                    max_3Ddistance -= 0.01;
            }
        }
        bool isRun=false;
        TimeSpan runtime;
        public void Start(TimeSpan t)
        {
            if (t == TimeSpan.Zero)
            {
                UpdateToTime(t);
                runtime = t;
            }
            else
            {
                runtime = new TimeSpan();
                UpdateToTime(runtime);
            }
            isRun = true;
        }
        public void UpdateToTime(TimeSpan t)
        {
            texttime.Text = t.Minutes + ":" + t.Seconds + ":" + t.Milliseconds;
        }
        Random random = new Random((int)DateTime.Now.Ticks);
        private void Test_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            AddGold();
        }
        
        void AddGold()
        {
            var gold = new Gold();
            if (random.Next(100) >= 70)
                gold.ThisGlodType = EmGoldType.Gold;
            int mx = 12;
            gold.Speed = mx / 2 - (random.NextDouble() + random.Next(0, mx));
            gold.JumpEndY = - random.Next(0, 100);
            gameCanvas.Children.Add(gold);
            gold.X = 200;
            gold.Y = 600;
            gold.BeginMove();
            //gold.OnClick = OnGlodClick; 
            if(isVibrate)
            vc.Start(TimeSpan.FromMilliseconds(100)); 

        }
        Microsoft.Devices.VibrateController vc = Microsoft.Devices.VibrateController.Default;  
        public void OnGlodClick(Gold g)
        {
            g.OnClick = null;
            var x = -(g.X);
            var y = (720 - g.Y);
            g.BeginMoveTo(x,y);
            g.OnMoveToEnd = OnGoldMoveToEnd;
        }
        public void OnGoldMoveToEnd(Gold g)
        {
            this.gameCanvas.Children.Remove(g);
            g.Dispose();
            if (g.ThisGlodType == EmGoldType.Gold)
                Scroce += 5;
            else
                Scroce += 1;
        }
        private int sroce;

        public int Scroce
        {
            get { return sroce; }
            set { sroce = value; textmoney.Text = (value).ToString(); }
        }

        protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
        {
            var pt = e.GetPosition(gameCanvas);
            OnMouseLeftDown(pt);
            base.OnMouseLeftButtonDown(e);
        }
        
        void gameCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var pt = e.GetPosition(gameCanvas);
            //OnMouseLeftDown(pt);
        }
        void Touch_FrameReported(object sender, TouchFrameEventArgs e)
        {
            var group = e.GetTouchPoints(gameCanvas);
            foreach (var item in group)
            {
                switch (item.Action)
                {
                    case TouchAction.Down:
                        OnMouseLeftDown(item.Position);
                        break;
                    case TouchAction.Move:
                        break;
                    case TouchAction.Up:
                        break;
                    default:
                        break;
                }
            }
        }
        public void OnMouseLeftDown(Point pt)
        {
            for (int i = 0; i < this.gameCanvas.Children.Count; i++)
            {
                if ((gameCanvas.Children[i] as Gold).IsD(pt))
                {
                    OnGlodClick(gameCanvas.Children[i] as Gold);
                    break;
                }
            }
        }
        bool isVibrate
        {
            get
            {
                var setting = System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings;
                if (setting.Contains("isVibrate"))
                {
                    return (bool)setting["isVibrate"];
                }
                else
                    return true;
            }
            set
            {
                var setting = System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings;
                if (setting.Contains("isVibrate"))
                    setting["isVibrate"] = value;
                else
                    setting.Add("isVibrate", value);
            }
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            isVibrate = !isVibrate;
            if (!isVibrate)
                Btn_isVibrate.Content = "Vibrate On";
            else
                Btn_isVibrate.Content = "Vibrate Off";
        }
    }
}
